import {ReadOrWriteError} from '../record';
import {Response} from "express";

const fs = require("fs");

export const getFileData = (filePath: string, res?: Response) => {
  const dataArr: string[] = [];
  return new Promise((resolve, reject) => {
    const option = {
      flags: "r",
      mode: 438,
      encoding: "utf-8",
      autoClose: true,
      start: 0,
      highWaterMark: 4
    };
    const readStream = fs.createReadStream(filePath, option);
    readStream.on("data", (chunk: Buffer | string) => {
      dataArr.push(chunk.toString());
    });
    readStream.on("close", () => {
      resolve(dataArr.join(""));
    });
    readStream.on("error", () => {
      reject(new ReadOrWriteError(`something run wrong during reading ${filePath}`, res));
    });
  });
};

export const saveFileData = (filePath: string, data: string, res?: Response) => {
  return new Promise((resolve, reject) => {
    const config = {
      flags: "w",
      encoding: "utf-8",
      fd: null,
      mode: 438,
      start: 0,
    };
    const writeStream = fs.createWriteStream(filePath, {encoding: "utf-8"});
    writeStream.on("error", () => {
      reject(new ReadOrWriteError(`something run wrong during writing ${filePath}`, res));
    });
    writeStream.on("finish", () => {
      resolve(true);
    });
    writeStream.write(data, "utf-8");
  });
};